const http = require('http');
const urllib = require('url');

const port = 10000;

const instance = http.createServer((req, res) => { // 创建服务，生成实例

  const params = urllib.parse(req.url, true);

  // 设置允许哪里来的源能够进行跨域 可以设置为 * 
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  // 缓存预检请求时间
  res.setHeader('Access-Control-Max-Age', '10');

  // 预检请求
  if (req.method === 'OPTIONS') {
    res.writeHead(200, {
      // 返回的设置头部要和请求的对应上哦
      'Access-Control-Allow-Headers': 'Content-Type, X-TOKEN',
    });

    return res.end();
  };

  res.writeHead(200, {
    'Content-Type': 'application/json; charset=utf-8',
    'Access-Control-Allow-Headers': 'Content-Type, X-TOKEN'
  });
  res.write(JSON.stringify({
    msg: 'success',
    code: 0
  }));
  res.end();
})

instance.listen(port, () => {
  console.log(`cors server is on: ${port}`)
})